package me.zhengjie.modules.weixin.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.zhengjie.config.entity.ResponseBaseEntity;
import me.zhengjie.config.enums.AtmrErrorEnum;
import me.zhengjie.config.exception.WeChatException;
import me.zhengjie.modules.weixin.service.IWechatOAuthService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("wechat/wechatOAuth")
@Api(tags = "WEB微信授权")
public class WechatOauthController {

    @Autowired
    private IWechatOAuthService wechatOAuthService;

    @RequestMapping("getOAuthUrl")
    @ApiOperation("WEB-获取微信授权URL")
    public String getOAuthUrl(String url,String scope) {
        String OAuthUrl = wechatOAuthService.getOAuthUrl(url,scope,"STATE");
        System.out.println("获取微信授权URL***"+OAuthUrl);
        return OAuthUrl;
    }


    @RequestMapping("getWxUserInfo")
    @ApiOperation("WEB-根据code获取微信用户信息")
    public ResponseBaseEntity getWxUserInfo(String code){
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            if (StringUtils.isBlank(code)){
                throw new WeChatException("code is blank");
            }
            WxOAuth2UserInfo wxUserInfo = wechatOAuthService.getWxUserInfo(code);
            response.setBody(wxUserInfo);
        }catch (WeChatException e){
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        }catch (Exception e){
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }

}
